package com.assic.utils.db.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author Ixion 往数据库写入文件<br>
 *         表结构 FILE_NAME FILE_DATA FILE_TYPE
 * 
 */
public class DBFileWriter {

	private static Connection conn;
	private static Statement statement;

	private static String tableName = "IOFD_FILE";

	/**
	 * 获取数据库连接并初始化statemrent
	 */
	static {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			Properties properties = new Properties();
			properties.load(DBFileWriter.class.getClassLoader()
					.getResourceAsStream("config/dataSource.properties"));
			conn = DriverManager.getConnection(
					properties.getProperty("db-url"),
					properties.getProperty("db-username"),
					properties.getProperty("db-password"));
			conn.setAutoCommit(false);// 禁止自动提交
			statement = conn.createStatement();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将文件保存到数据库
	 * 
	 * @param file
	 *            待保存文件
	 * @return 保存成功状态
	 * @throws SQLException
	 *             sql执行过程中出现问题将抛出
	 * @throws FileNotFoundException
	 *             待保存文件不存在
	 */
	public static boolean saveFile(File file) throws SQLException,
			FileNotFoundException {
		// 文件名
		String fileName = file.getName();
		// 文件扩展名
		String fileType = fileName.substring(fileName.lastIndexOf(".") + 1,
				fileName.length());
		// 真实文件名
		fileName = fileName.substring(0, fileName.lastIndexOf("."));
		// 判断是否存在文件的查询语句
		String SELECT = "SELECT  FILE_NAME FROM " + tableName
				+ " WHERE FILE_NAME = '" + fileName + "' AND FILE_TYPE = '"
				+ fileType + "'";
		// 执行判断
		ResultSet r = statement.executeQuery(SELECT);
		if (r.next()) {
			throw new RuntimeException("文件已经存在,请更换文件名再试");
		}
		String INSERT = "INSERT INTO " + tableName
				+ "(FILE_NAME,FILE_DATA,FILE_TYPE) VALUES('" + fileName
				+ "',EMPTY_BLOB(),'" + fileType + "')";
		// 执行插入空BLOB
		int rt = statement.executeUpdate(INSERT);
		String SUPDATE = "SELECT FILE_DATA FROM " + tableName
				+ " WHERE FILE_NAME = '" + fileName + "' AND FILE_TYPE = '"
				+ fileType + "' FOR UPDATE";
		// 如果插入成功 查询出来进行BOLB写入
		if (rt > 0) {
			ResultSet rs = statement.executeQuery(SUPDATE);// 查出数据用于写入流
			if (rs.next()) {
				Blob b = rs.getBlob("FILE_DATA");
				BufferedOutputStream bs = new BufferedOutputStream(
						b.setBinaryStream(0L));
				BufferedInputStream bis = new BufferedInputStream(
						new FileInputStream(file));
				// 流对接
				int bytes;
				try {
					while ((bytes = bis.read()) != -1) {
						bs.write(bytes);
					}
					bis.close();
					bs.close();
					conn.commit();// 提交
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			} else {
				return false;
			}
		}
		return true;

	}

}
